package org.september.pisces.user.permission.service;

import java.util.HashMap;
import java.util.Map;

import org.september.pisces.user.permission.utils.UserSessionHelper;
import org.september.simpleweb.utils.SessionHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserOnlineStatusService {

	/**
	 * key: 用户Id
	 * value: 心跳时间
	 */
	private static Map<Long,Long> webUserHeartBeatMap = new HashMap<>();
	
	private static Map<Long,String> currentUserWebSidMap = new HashMap<>();
	
	/**
	 * AppUser
	 * key: 用户Id
	 * value: 心跳时间
	 */
	private static Map<Long,Long> appUserHeartBeatMap = new HashMap<>();
	
	public void webUserHeartBeat(Long uid) {
		webUserHeartBeatMap.put(uid, System.currentTimeMillis());
		//如果数据库的sid和当前sid不一致，则当前用户退出
		if(!SessionHelper.getSession().getId().equals(currentUserWebSidMap.get(uid))) {
			UserSessionHelper.remove();
			removeUser(uid);
		}
	}
	
	public void removeUser(long uid) {
		webUserHeartBeatMap.remove(uid);
	}
	
	public boolean isUserWebOnline(Long uid) {
		if(!webUserHeartBeatMap.containsKey(uid)) {
			return false;
		}
		Long timegap = System.currentTimeMillis() - webUserHeartBeatMap.get(uid);
		if(timegap>120*1000) {
			return false;
		}
		return true;
	}
	
	public void appUserHeartBeat(Long uid) {
		appUserHeartBeatMap.put(uid, System.currentTimeMillis());
	}
	
	public boolean isUserAppOnline(Long uid) {
		if(!appUserHeartBeatMap.containsKey(uid)) {
			return false;
		}
		Long timegap = System.currentTimeMillis() - appUserHeartBeatMap.get(uid);
		if(timegap>120*1000) {
			return false;
		}
		return true;
	}
	
	public static void setCurrentUserSid(Long uid , String sid) {
		currentUserWebSidMap.put(uid, sid);
	}
}
